from flask import Flask, render_template, request, redirect, url_for, make_response
from flask_login import (
    LoginManager,
    login_user,
    logout_user,
    login_required,
    current_user,
)
from flask_migrate import Migrate
from models import db, User, Post, Tag, Category
from datetime import datetime
from config import Config

# ==========================
# 初始化扩展插件
# ==========================
migrate = Migrate()
login_manager = LoginManager()
# login_manager.login_view = 'auth.login'

# ==========================
# 创建应用实例
# ==========================
app = Flask(__name__)
app.config.from_object(Config)

# 绑定扩展
db.init_app(app)
migrate.init_app(app, db)
login_manager.init_app(app)


# 获取当前已登录的用户
@login_manager.user_loader
def load_user(user_id):
    return db.session.get(User, user_id)


# ------------------------
# 初始化数据库和管理员
# ------------------------
with app.app_context():
    db.create_all()
    if not User.query.filter_by(username="admin").first():
        admin = User(username="admin", password="1234")  # 明文仅测试用
        db.session.add(admin)
        db.session.commit()
        print("管理员创建成功")


# ------------------------
# 路由开始
# ------------------------
@app.route("/")
@app.route("/page/<int:page>")
def index(page=1):
    per_page = request.args.get(
        "per_page", int(request.cookies.get("per_page", 5)), type=int
    )
    pagination = Post.query.filter_by(status='published').order_by(Post.created_at.desc()).paginate(
        page=page, per_page=per_page
    )
    response = make_response(
        render_template(
            "index.html",
            posts=pagination.items,
            pagination=pagination,
            per_page=per_page,
        )
    )
    response.set_cookie(
        "per_page", str(per_page), max_age=60 * 60 * 24 * 30
    )  # 记住 30 天
    return response

@app.route("/admin")
@app.route("/admin/page/<int:page>")
@login_required
def admin_index(page=1):
    per_page = request.args.get(
        "per_page", int(request.cookies.get("per_page", 5)), type=int
    )
    pagination = Post.query.order_by(Post.created_at.desc()).paginate(
        page=page, per_page=per_page
    )
    response = make_response(
        render_template(
            "admin_index.html",  # 可以和 index.html 共用也行
            posts=pagination.items,
            pagination=pagination,
            per_page=per_page,
            is_admin=True,
        )
    )
    response.set_cookie("per_page", str(per_page), max_age=60 * 60 * 24 * 30)
    return response

@app.route("/go_to_page", methods=["POST"])
def go_to_page():
    page = request.form.get("page")
    per_page = request.form.get("per_page", 5)
    from_admin = request.form.get("from_admin") == "1"
    if page and page.isdigit():
        return redirect(url_for("admin_index" if from_admin else "index", page=int(page), per_page=per_page))
    return redirect(url_for("admin_index" if from_admin else "index", per_page=per_page))

@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "POST":
        username = request.form["username"]
        password = request.form["password"]
        user = User.query.filter_by(username=username).first()
        if user and user.password == password:
            login_user(user)
            return redirect(url_for("admin_index"))
    return render_template("login.html")


@app.route("/logout")
def logout():
    logout_user()
    print(url_for("index"))
    return redirect(url_for("index"))


@app.route("/create", methods=["GET", "POST"])
@login_required
def create():
    if request.method == "POST":
        title = request.form["title"]
        content = request.form["content"]
        category_id = request.form["category_id"]
        tag_names = request.form["tags"].split(" ")
        created_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        status = request.form["status"]
        
        post = Post(
            title=title,
            content=content,
            user_id=current_user.id,
            category_id=category_id,
            created_at=created_at,
            status=status,
        )

        tags = []
        for name in tag_names:
            name = name.strip()
            if name:
                tag = Tag.query.filter_by(name=name).first()
                if not tag:
                    tag = Tag(name=name)
                    db.session.add(tag)
                tags.append(tag)

        post.tags = tags

        db.session.add(post)
        db.session.commit()
        return redirect(url_for("admin_index"))

    categories = Category.query.all()
    return render_template("create.html", categories=categories)


@app.route("/post/<int:post_id>")
def post(post_id):
    post = Post.query.get_or_404(post_id)
    print(post)
    return render_template("post.html", post=post)


@app.route("/edit/<int:post_id>", methods=["GET", "POST"])
def edit(post_id):
    print(post_id)
    post = Post.query.get_or_404(post_id)
    if request.method == "POST":
        post.title = request.form["title"]
        post.content = request.form["content"]
        category_id = request.form["category_id"]
        tag_names = request.form["tags"].split(" ")
        status = request.form.get('status', 'draft')
        tags = []
        for name in tag_names:
            name = name.strip()
            if name:
                tag = Tag.query.filter_by(name=name).first()
                if not tag:
                    tag = Tag(name=name)
                    db.session.add(tag)
                tags.append(tag)

        post.tags = tags
        post.category_id = category_id
        post.status = status

        db.session.commit()
        return redirect(url_for("post", post_id=post.id))
    
    categories = Category.query.all()
    return render_template("edit.html", post=post, categories=categories)


if __name__ == "__main__":
    app.run(debug=True)
